package hw2.nsl;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

public class NetworkMessage implements Serializable
{

    /**
	 * 
	 */
    private static final long serialVersionUID = 4128527765763941793L;

    // the message to be transmitted
    public byte[] text;

    // the source of the message
    public String source;

    /**
     * 
     * @return a string array of all fields
     */
    public String[] parseFields() {
        String str = new String( text );
        return str.split( "\\s+" );
    }

    /**
     * 
     * @param text
     *            the byte array
     * @param source
     *            the source of the message
     */
    public NetworkMessage( byte[] text, String source ) {
        this.text = text;
        this.source = source;
    }

    /**
     * hex representation of the byte array
     */
    public String toHexString() {
        String result = new String();
        int tmp = 0;
        String temp = null;
        for( int i = 0; i < text.length; i++ ) {
             tmp = text[i] & 0xFF;
             temp = Integer.toHexString(tmp);
             if(temp.length() == 1){
             temp = "0" + temp;
             }
            
            //if(i%2 == 0){
                 result += " \\x";
           //}
             result += temp;
            //result += "\\u" + Long.toHexString( (long) text[i] );
        }
        result = result.trim();
        return result;
    }
    
    /**
     * String representation of the byte array
     * 
     */
    public String toByteString(){
        String result = null;
        try {
            result =  new String(text, "UTF-8");
        } catch( UnsupportedEncodingException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}   
